<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>共享文件</title>
  <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" />
</head>
<body>
  <div id="app" class="container py-4">
    <h3 class="mb-3">来自 {{ fromUsername }} 的分享</h3>
    <div v-if="error" class="alert alert-danger">{{ error }}</div>

    <!-- 密码验证表单 -->
    <div v-if="needPassword" class="card">
      <div class="card-body">
        <h5 class="card-title">需要访问密码</h5>
        <p class="text-muted">此分享链接已设置访问密码，请输入4位数字密码</p>
        <div class="mb-3">
          <label class="form-label">访问密码</label>
          <input type="text" class="form-control" v-model="password" 
                 maxlength="4" pattern="[0-9]{4}" placeholder="请输入4位数字密码" 
                 @keyup.enter="verifyPassword" />
        </div>
        <button class="btn btn-primary" @click="verifyPassword" :disabled="passwordVerifying">
          {{ passwordVerifying ? '验证中...' : '验证密码' }}
        </button>
        <div v-if="passwordError" class="text-danger mt-2">{{ passwordError }}</div>
      </div>
    </div>

    <!-- 文件信息 -->
    <div v-if="file && !needPassword">
      <div class="card">
        <div class="card-body d-flex align-items-center justify-content-between">
          <div>
            <div class="fw-bold">{{ file.name }}</div>
            <div class="text-muted">{{ file.is_dir ? '目录' : (file.mime_type || '文件') }} · {{ formatSize(file.size) }}</div>
          </div>
          <div>
            <button v-if="!file.is_dir" class="btn btn-primary" @click="download">下载</button>
            <span v-else class="text-muted">暂不支持目录下载</span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script>
    const { createApp, ref } = Vue
    createApp({
      setup() {
        const fromUsername = ref('')
        const file = ref(null)
        const error = ref('')
        const needPassword = ref(false)
        const password = ref('')
        const passwordVerifying = ref(false)
        const passwordError = ref('')
        const shareToken = ref('') // 保存验证后获得的 share_token
        const token = new URLSearchParams(location.search).get('token') || ''

        const fetchInfo = async () => {
          try {
            const res = await axios.get(`/api/v1/share/${token}`)
            
            // 检查是否需要密码
            if (res.data.has_password === true) {
              needPassword.value = true
              fromUsername.value = res.data.from_username || ''
              file.value = res.data.file
              return
            }
            
            fromUsername.value = res.data.from_username || ''
            file.value = res.data.file
          } catch (e) {
            error.value = e.response?.data?.error || e.message
          }
        }

        const verifyPassword = async () => {
          if (!password.value || password.value.length !== 4) {
            passwordError.value = '密码必须是4位数字'
            return
          }
          
          passwordVerifying.value = true
          passwordError.value = ''
          
          try {
            const res = await axios.post('/api/v1/share/verify-password', {
              token: token,
              password: password.value
            })
            
            // 保存 share_token，用于后续请求
            shareToken.value = res.data.share_token
            
            // 重新获取文件信息（带 token）
            const infoRes = await axios.get(`/api/v1/share/${token}`, {
              headers: {
                'X-Share-Token': shareToken.value
              }
            })
            
            fromUsername.value = infoRes.data.from_username || ''
            file.value = infoRes.data.file
            needPassword.value = false
          } catch (e) {
            passwordError.value = e.response?.data?.error || '密码验证失败'
          } finally {
            passwordVerifying.value = false
          }
        }

        const download = () => {
          const url = `/api/v1/share/${token}/download`
          if (shareToken.value) {
            // 带 share_token 下载
            fetch(url, {
              headers: {
                'X-Share-Token': shareToken.value
              }
            }).then(response => {
              if (response.ok) {
                return response.blob()
              }
              throw new Error('下载失败')
            }).then(blob => {
              const url = window.URL.createObjectURL(blob)
              const a = document.createElement('a')
              a.href = url
              a.download = file.value.name
              document.body.appendChild(a)
              a.click()
              document.body.removeChild(a)
              window.URL.revokeObjectURL(url)
            }).catch(err => {
              console.error('下载失败:', err)
              alert('下载失败')
            })
          } else {
            // 无需密码，直接下载
            window.open(url, '_blank')
          }
        }

        const formatSize = (bytes) => {
          if (!bytes) return '0 B'
          if (bytes < 1024) return bytes + ' B'
          if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
          return (bytes / 1024 / 1024).toFixed(1) + ' MB'
        }

        fetchInfo()
        return { fromUsername, file, error, download, formatSize, needPassword, password, passwordVerifying, passwordError, verifyPassword }
      }
    }).mount('#app')
  </script>
</body>
</html>


